#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time          : 2023/2/21 9:18
# File          : web_flask.py
# @Author       : MingTai
# @Department   : platform_qa
# 做API服务后端，主要是三块内容：路由，数据库，身份验证。（不需要 渲染 这块东西了）
from flask import Flask
from flask import jsonify
from flask import request
from Tools.dbmanager import DBManager
from Tools.decoratormanager import session_jwt_verification

app = Flask(__name__)


@app.route("/bumen", methods=['GET'])
@session_jwt_verification
def goto_bumen_search():
    ###############查询部门###############
    sqlstring0 = "SELECT id,bumenname,bumentips FROM jr_bumen"
    data0 = DBManager().executeQueryall(sqlstring0)
    if data0 == False:
        return_data = dict()
        return_data['code'] = 5000
        return_data['msg'] = "数据库连接异常！"
        return jsonify(return_data)
    if data0 == None:
        return_data = dict()
        return_data['code'] = 5001
        return_data['msg'] = "没有部门数据！"
        return jsonify(return_data)
    if data0 != None:
        return_data = dict()
        return_data['code'] = 200
        return_data['msg'] = "查询成功！"
        return_data['bumendatas'] = data0
        return jsonify(return_data)


@app.route("/bumen", methods=['POST'])
@session_jwt_verification
def goto_bumen_add():
    data = request.get_json()
    bumen_name = data['bumenName']
    bumen_tips = data['bumenTips']
    ###############新增部门###############
    sqlstring0 = f"INSERT INTO jr_bumen (bumenname,bumentips) VALUES ('{bumen_name}','{bumen_tips}')"
    data0 = DBManager().executeQueryID(sqlstring0)
    if data0 == False:
        return_data = dict()
        return_data['code'] = 5000
        return_data['msg'] = "数据库连接异常！"
        return jsonify(return_data)
    if data0 != None:
        return_data = dict()
        return_data['code'] = 200
        return_data['msg'] = "部门添加成功！"
        return_data['bumenid'] = data0
        return jsonify(return_data)


@app.route("/bumen", methods=['PUT'])
@session_jwt_verification
def goto_bumen_alter():
    data = request.get_json()
    bumen_id = data['bumenId']
    bumen_name = data['bumenName']
    bumen_tips = data['bumenTips']
    ###############更新部门###############
    sqlstring0 = f"UPDATE jr_bumen SET bumenname='{bumen_name}',bumentips='{bumen_tips}' WHERE id= {bumen_id}"
    data0 = DBManager().executeQueryNO(sqlstring0)
    if data0 == False:
        return_data = dict()
        return_data['code'] = 5000
        return_data['msg'] = "数据库连接异常！"
        return jsonify(return_data)
    if data0 == True:
        return_data = dict()
        return_data['code'] = 200
        return_data['msg'] = "部门修改成功！"
        return jsonify(return_data)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
